<?php

namespace Biz\service\activity;


use Biz\cache\lottery\CCreateWikiList;
use Biz\model\activity\ActivityAwardDelivery;
use Biz\model\advertisement\goodbuy\MActivityGoodBuyWiki;
use Biz\model\advertisement\goodbuy\MActivityGoodBuyWikiRecommend;
use Biz\model\ShopFavorite as mShopFavorite;
use Biz\service\activity\lottery\LotteryActivityMsg;
use Biz\tools\helper\Common;
use Doraemon\model\ForbiddenWord\ForbiddenSceneWord as ForbiddenSceneWordModel;
use Doraemon\pockets\constInterface\statSign\AutoPlatformModule;
use Doraemon\service\ForbiddenWord\ForbiddenSceneWord;
use Doraemon\service\statSign\Basic;
use Doraemon\tools\HhzEnv;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\Log;
use Exception;

class CreateWikiList
{
    private static array $instance = [];
    private static array $rankCoverImg = [];
    private $uid;
    private $did;
    private $activity_id = ActivityAwardDelivery::ACTIVITY_CREATE_WIKI_LIST;
    private $shareTaskMaxTimes = 0;
    private $createTaskMaxTimes = 0;
    private $hostUids = [];
    private $pvTask = 'pv';
    private $shareTask = '';
    private $createTask = '';
    private $lotteryTask = '';
    private string $winnerTask = '';
    private array $topicConfig;
    private array $awardsConfig;
    private array $awardWikiIds;
    private $gap_lock;
    private array $err = [];
    private $cache_handler;
    private $activity_end_date;
    private $date;

    /**
     * @return string
     */
    public function getActivityEndDate(): string
    {
        return $this->activity_end_date;
    }

    /**
     * @return false|string
     */
    public function getDate()
    {
        return $this->date;
    }

    /**
     * @param $uid
     * @param int $activity_id
     * @param int $shareTaskMaxTimes
     * @param int $createTaskMaxTimes
     */
    public function __construct($uid, $did, int $activity_id, int $shareTaskMaxTimes, int $createTaskMaxTimes, array $hostUids)
    {
        $this->uid = $uid;
        $this->did = $did;
        $this->activity_id = $activity_id;
        $this->shareTaskMaxTimes = $shareTaskMaxTimes;
        $this->createTaskMaxTimes = $createTaskMaxTimes;
        $this->cache_handler = new CCreateWikiList;
        $this->hostUids = $hostUids;
        $this->topicConfig();
        $this->awardConfig();
        $this->date = date("Ymd");
        $this->shareTask = $this->shareKey($this->date);
        $this->createTask = $this->createKey($this->date);
        $this->lotteryTask = $this->lotteryKey($this->date);
        $this->winnerTask = $this->winnerKey($this->uid);
        $this->activity_end_date = '20221112';
    }

    public function __destruct()
    {
        if ($this->gap_lock) CCreateWikiList::unlock($this->gap_lock);
        if ($this->err && $this->activityLiving()) {
//            $this->cache_handler::pushLog($this->uid . "[" . $this->now() . "]:" . implode("|", $this->err));
            Log::info('CCreateWikiListLog', ['data' => $this->uid . "[" . $this->now() . "]:" . implode("|", $this->err)]);
        }
    }

    public function activityLiving(): bool
    {
        return $this->date < $this->activity_end_date;
    }

    /**
     * @return int
     */
    public function getShareTaskMaxTimes(): int
    {
        return $this->shareTaskMaxTimes;
    }

    /**
     * @return int
     */
    public function getCreateTaskMaxTimes(): int
    {
        return $this->createTaskMaxTimes;
    }

    public function awardConfig()
    {
        $this->awardsConfig = [
            190395 => [190395,'迷你吸尘器','https://img.haohaozhu.cn/Op-imageShow/2b44f308g08g0h800rkekea?iv=1','https://img.haohaozhu.cn/Op-imageShow/8d42630ku0ku0w900rk8lw1?iv=1'],
            65850 => [65850,'十八纸装饰圣诞树','https://img.haohaozhu.cn/Op-imageShow/9ee5e308g08g01N00rkekex?iv=1','https://img.haohaozhu.cn/Op-imageShow/9626630m80m80VH00rk8lxy?iv=1'],
            270579 => [270579,'儿童床头柜','https://img.haohaozhu.cn/Op-imageShow/83f36308g08g0Tm00rkekcv?iv=1','https://img.haohaozhu.cn/Op-imageShow/8579d30k00k00Y000rk8lzb?iv=1'],
            159339 => [159339,'空气质量检测仪','https://img.haohaozhu.cn/Op-imageShow/752b8308g08g0Hi00rkekdi?iv=1','https://img.haohaozhu.cn/Op-imageShow/9ac3b20ku0ku0MY00rkekg2?iv=1'],
            234347 => [234347,'厚米编织袋','https://img.haohaozhu.cn/Op-imageShow/2866c308g08g0YF00rkt63x?iv=1',''],
            126751 => [126751,'「住二代」限定小相机抱枕','https://img.haohaozhu.cn/Op-imageShow/21d5a308g08g0pV00rkt649?iv=1',''],
            '20元京东卡' => ['20元京东卡','20元京东卡','https://img.haohaozhu.cn/Op-imageShow/86eed308g08g0e400rkt63j?iv=1',''],
        ];

        $this->awardWikiIds = array_column($this->awardsConfig, '0');
    }

    public function topicConfig(): array
    {
        /**
         * c928e30v90ma0Vj00rk3nul ae34a30sl0sl0O800rk3nwv 210c720v90l80WW00rkcqwk
         * 210a730v90ma0oT00rk3nxn 3b42230sl0sl02y00rk3nz1 21a9f20v90l80X500rkcqyq
         * 8823e30v90ma0Mb00rk3nzu fab9830sl0sl02z00rk3o0a 6cfb020v90l80M500rkcqz4
         * 7603330v90ma0Pf00rk3o1i 886e430sl0sl0Hd00rk3o1w 3260b20v90l803Q00rkcqzh
         * fa8d130v90ma0eg00rk3o2d 3831630sl0sl03200rk3o2o 4260820v90l809200rkcqzs
         * 61cb730v90ma0PZ00rk3o3d 639d930sl0sl0Fp00rk3o3r 3214720v90l80WJ00rkcr05
         * 5970430v90ma0gy00rk3o44 1071d30sl0sl0om00rk3o4g 7da1220v90l80Xz00rkcr0i
         */
        return $this->topicConfig = [
            1 => [
                '1',
                '颜控最爱｜时髦软装大集合',
                'https://img.haohaozhu.cn/Op-imageShow/c928e30v90ma0Vj00rk3nul?iv=1',
                'https://img.haohaozhu.cn/Op-imageShow/db50830sl0sl0It00rkpmcz?iv=1',
                'https://img.haohaozhu.cn/Op-imageShow/210c720v90l80WW00rkcqwk?iv=1',
                'niceliving://topic/detail?protego=eyJ0b3BpY19pZCI6IjE2NTMiLCJzZWFyY2hfdHlwZSI6IjEiLCJzb3J0X3R5cGUiOiIxIn0%3D',
                ['00603z10000650is','00602wa00001e2q3','00601vm00000xb95','005zu1900000l3yq','005zulw00004otw7','005zwjf00008w7vq','005zwb900000xjdy','005zvgj00003ep53','005zxg200000qike','005zzvy00004m6zd','00601jj000003270','00602zh00007o2mm','00602wr00007o2mm','00604gl000010tje','0060451000073515','00603cz0000192ir','00603bp000010ue4','006079p00004t5n8','0060754000084rtw','006083u000000ux4',],
                1653,
            ],
            2 => [
                '2',
                '懒人好物｜让科技解放双手',
                'https://img.haohaozhu.cn/Op-imageShow/210a730v90ma0oT00rk3nxn?iv=1',
                'https://img.haohaozhu.cn/Op-imageShow/211b730sl0sl02u00rkpme6?iv=1',
                'https://img.haohaozhu.cn/Op-imageShow/21a9f20v90l80X500rkcqyq?iv=1',
                'niceliving://circle/detail?protego=eyJpZCI6IjI3In0%3D',
                ['0060132000000a9s','00603kl00000n19a','00601ai00004fx76','005zxqz00000p7ub','005zurd00008axxm','00607x8000006b3d','00605an00007pmnn','00606op00000ghny','00606dy000052tzo',],
                27,
            ],
            3 => [
                '3',
                '收纳神器｜体验秩序的快乐',
                'https://img.haohaozhu.cn/Op-imageShow/8823e30v90ma0Mb00rk3nzu?iv=1',
                'https://img.haohaozhu.cn/Op-imageShow/add2330sl0sl0IL00rkpmes?iv=1',
                'https://img.haohaozhu.cn/Op-imageShow/6cfb020v90l80M500rkcqz4?iv=1',
                'niceliving://circle/detail?protego=eyJpZCI6IjIzIn0%3D',
                ['006016g00004vpxa','006066t00000vnzr','006061t00002ewd6','00608lp00002ewd6','006084d000000mvt','006063300006rp4p','00606010000704g9','00604j100005bw46','00604av00006v99w',],
                23,
            ],
            4 => [
                '4',
                '厨房好物｜居家下厨的法宝',
                'https://img.haohaozhu.cn/Op-imageShow/7603330v90ma0Pf00rk3o1i?iv=1',
                'https://img.haohaozhu.cn/Op-imageShow/4b02230sl0sl0vE00rkpmff?iv=1',
                'https://img.haohaozhu.cn/Op-imageShow/3260b20v90l803Q00rkcqzh?iv=1',
                'niceliving://circle/detail?protego=eyJpZCI6IjcifQ%3D%3D',
                ['00607c3000017gw4','0060685000001d7o','00605ue000001yet','006065q00000vnzr','006062200003o4w5','00608r0000010eph','00608j300008kec7','0060e8100003k9pd','0060e8300004vpxa',],
                7,
            ],
            5 => [
                '5',
                '吧台好物｜宅家续命必备',
                'https://img.haohaozhu.cn/Op-imageShow/fa8d130v90ma0eg00rk3o2d?iv=1',
                'https://img.haohaozhu.cn/Op-imageShow/0a61a30sl0sl0Tq00rkpmg1?iv=1',
                'https://img.haohaozhu.cn/Op-imageShow/4260820v90l809200rkcqzs?iv=1',
                'niceliving://circle/detail?protego=eyJpZCI6IjcifQ%3D%3D',
                ['00602m5000008410','006018s000009nmu','006007e00008v3cu','00602z100006b433','006028l000006jwn','006017j000082633','005zzt000000d1ap','005zyjn00008pn32','005zydw00000l3yq','005zwlu00001ukan','005zvht00000xjdy','005zuup00001rwal','00606lh00002yj5c',],
                7,
            ],
            6 => [
                '6',
                '养宠好物｜主子们用了都说好',
                'https://img.haohaozhu.cn/Op-imageShow/61cb730v90ma0PZ00rk3o3d?iv=1',
                'https://img.haohaozhu.cn/Op-imageShow/d5a6630sl0sl0xJ00rkpmgg?iv=1',
                'https://img.haohaozhu.cn/Op-imageShow/3214720v90l80WJ00rkcr05?iv=1',
                'niceliving://circle/detail?protego=eyJpZCI6IjE4In0%3D',
                ['006006000002gzrw','00606du00002qln3','00603yf00004jzl3','0060e6l00005dgex','0060e5h00004q4ob','0060dhv00004jzl3','0060clq000001yet','0060bpf00004nk7o','0060ary00002mzkd',],
                18,
            ],
            7 => [
                '7',
                '园艺好物｜植物养护的扛把子',
                'https://img.haohaozhu.cn/Op-imageShow/5970430v90ma0gy00rk3o44?iv=1',
                'https://img.haohaozhu.cn/Op-imageShow/58d6230sl0sl0nS00rkpmgv?iv=1',
                'https://img.haohaozhu.cn/Op-imageShow/7da1220v90l80Xz00rkcr0i?iv=1',
                'niceliving://circle/detail?protego=eyJpZCI6IjIifQ%3D%3D',
                ['006040r000000sg7','00601ac000060zny','005zqcf000056lad','005zqcm00008wp23','00607hu00001uclb','0060609000035hy0','006020q00003is86','0060akk00000ghny','0060e3n0000143cg',],
                2,
            ],
        ];
    }

    public static function getInstance($uid = 0, $did = '', $config = 0): ?CreateWikiList
    {
        if (empty(self::$instance[$uid])) {
            $hostUids = [
                11975,184404,596897,457193,135178,2290106,844941
            ];
            //活动时间 2022年11月4日0点-11月11日24点

            self::$instance[$uid] = new self($uid, $did, ActivityAwardDelivery::ACTIVITY_CREATE_WIKI_LIST, 1, 2, $hostUids);
        }
        return self::$instance[$uid];
    }

    public function pv($topic_id)
    {
        if (empty($topic_id)) return;
        if (!$this->activityLiving()) return;
        $init = $this->getPv($topic_id);
        //pv 200-500之间随机取一个兜底数+清单页面PV
        $value = $init ? 1 : rand(200, 500);
        CCreateWikiList::incrTaskCounter($this->pvTask, $topic_id, $value);
    }

    public static function rankCoverImg($num = 3): array
    {
        if (empty(self::$rankCoverImg)) {
            $img = \Biz\module\Classes\wiki\Wiki::getRandUserCoverImg(21);
            self::$rankCoverImg = empty($img) ? [] : array_column($img, 'cover_img');
        }
        shuffle(self::$rankCoverImg);
        return array_slice(self::$rankCoverImg, 0, $num);
    }

    public function record($message = '')
    {
        $this->err[] = $message;
    }

    public function getPv($topic_id)
    {
        return CCreateWikiList::getTaskCounter($this->pvTask, $topic_id);
    }

    public function allPv(): array
    {
        return CCreateWikiList::getAllTask($this->pvTask);
    }

    /**
     * @throws Exception
     */
    public function createGuidance($topic_id, $wiki, $recommend, $top = 0, $cli = false)
    {
        if (empty($this->uid)) throw new \Exception('登录后操作');
        if (!$cli) $this->record('创建清单,参数' . json_encode(compact('topic_id', 'wiki', 'recommend', 'top'), JSON_UNESCAPED_UNICODE));
        $recommend = trim($recommend);
        if (empty($wiki)) throw new Exception('你还未添加商品哦～');
        if (strlen($recommend) == 0) throw new Exception('说说你为什么推荐ta吧');
        if (HhzEnv::isProduction() && (!$cli)) $this->wordTrial($recommend);
        try {
            //新增记录
            MActivityGoodBuyWiki::action(function () use ($topic_id, $wiki, $top, $recommend) {
                $uniCondition = ['topic_id' => $topic_id, 'wiki_id' => $wiki];
                $created_at = $this->now();
                $updated_at = $this->now();
                $uid = $this->uid;
                $info = MActivityGoodBuyWiki::get('*', $uniCondition);
                $id = $info['id'] ?? 0;
                if ($info) {
                    $add = MActivityGoodBuyWiki::update(['num[+]' => 1, 'updated_at' => $updated_at], ['id' => $info['id']])->rowCount();
                    if (!$add) throw new Exception('更新清单失败');
                } else {
                    $num = 1;
                    $data = $uniCondition + compact('uid', 'recommend', 'num', 'top', 'created_at', 'updated_at');
                    $add = MActivityGoodBuyWiki::insert($data)->rowCount();
                    if (!$add) throw new Exception('添加清单失败');
                    $id = MActivityGoodBuyWiki::id();
                }
                $add = MActivityGoodBuyWikiRecommend::insert($uniCondition + compact('uid', 'recommend','created_at', 'updated_at'))->rowCount();
                if (!$add) throw new Exception('添加推荐语失败');
                //创建最热排行榜 + 推荐语倒序
                CCreateWikiList::incrRankScore($topic_id, $id);
            });
            if (!$cli) $this->finishCreateTask();
            $this->record('创建清单获取抽奖次数 +1');
        } catch (\Exception $e) {
            $this->record('创建清单失败原因,' . $e->getMessage());
        }
    }

    public function appendGift()
    {
        $conf = [
            '20221105' => [234347,234347,234347,234347,234347],
            '20221106' => [126751],
            '20221107' => ['20元京东卡','20元京东卡'],
            '20221108' => [234347,234347,234347,234347,234347],
            '20221109' => ['20元京东卡'],
            '20221110' => ['20元京东卡'],
            '20221111' => ['20元京东卡'],
        ];
        $now = date("Ymd");
        $exists = CCreateWikiList::hasGiftPool($now);
        if (empty($exists)) {
            $gift = $conf[$now] ?? [];
            if ($gift) {
                CCreateWikiList::generateGiftPool($now, $gift);
                CCreateWikiList::generateGiftPool('', $gift);
                $this->record("$now 追加商品:" . implode(",", $gift));
            }
        }
    }

    public static function initGiftPool()
    {
        CCreateWikiList::clearGiftPool();
        $gift = [65850, 65850, 270579, 190395, 190395, 159339, 159339];
        shuffle($gift);
        CCreateWikiList::generateGiftPool('', $gift);
        echo "初始化完成,奖品池如下:", PHP_EOL;
        echo implode(',', CCreateWikiList::getGiftPool());
    }

    public static function prepareGuidance()
    {
        $config = [
            11975 => [
                [1, 270143, '这盏台灯设计于1945年，每一片遮光板都可以转动，灯光可以根据需求自由扩散，有着浓厚的现代气息。'],
                [1, 270140, '喜欢这盏落地灯沉静克制的气质，拉绳式开关富有趣味。'],
                [1, 270141, '大师经典设计，纸绳编织带来的自然气息让人着迷！'],
            ],
            184404 => [
                [2, 5161, '湿垃圾再见了您～垃圾处理器绝对是必备懒人家电，这款运行声音超级小！预算不够的e100也不错。'],
                [2, 254916, '家里有娃的，一人独居的，这个锅就是一个完美！功能多还不占地方，在我家利用率超高！'],
                [2, 259760, '拖地届扛把子！新出的鲸灵托管模式彻底解放双手，地板干净到我妈都自愧不如！'],
            ],
            596897 => [
                [3, 270245, '便于收纳，大人宝宝都适用的多功能折叠凳。室内可用于拿取衣柜橱柜高处物品，户外轻便易携。'],
                [3, 270244, '46.5的进深，适合大部分空间的橱柜。高度和宽度变化支持模块叠加。明显改善家居杂乱环境。'],
                [3, 192275, '可利用橱柜鸡肋空间，将日常回收塑料袋快捷收纳。有效提高家务效率。还可收纳雨伞、薄垫等物品。'],
            ],
            457193 => [
                [4, 270243, '四川人的真爱那必须是火锅，在家吃火锅的美好大抵只有我们自己知道，这美好的烟火气可真迷人啊！'],
                [4, 70294, '我家的大白管家，开放式厨房的颜值担当！超大容量满足三代同堂五口之家的食物储存！'],
                [4, 270145, '颜值与实力并存YYDS，使用三年多我的开放式厨房依然一尘不染！'],
            ],
            14737390 => [
                [4, 271753, '你见过能吸PM2.5的油烟机吗？爆炒辣椒一点味道都没有的那种。安装了PM2.5传感器的米家净烟机真是香！'],
            ],
            135178 => [
                [5, 270246, '个人很喜欢的一套咖啡手冲壶套装，好看好用易搭配，容量适中，是在家使用频率最高的一套。'],
                [5, 12681, '手冲爱好者对Fellow手冲咖啡壶应该都不会陌生，温控精确，很好上手，奶乎乎的米白色很难不心动。'],
                [5, 251245, '这个收纳架自带两个小收纳篮，上面放水壶，下面放些零碎物品，做为咖啡角的补充收纳很合适。'],
            ],
            2290106 => [
                [6, 65042, '激发猫咪好奇心的小玩具，可以随时随地吸引猫咪的注意力，可以玩很长时间且乐此不疲。'],
                [6, 93383, '懒人铲屎官不可多得的小助手，从此告别铲屎，解放双手。'],
                [6, 270052, '可以移动的陪伴机器人，在家中无人的时候可以去到各个角落，还可以代替我跟猫咪一起玩耍。'],
            ],
            844941 => [
                [7, 64055, '半透明的外观能一目了然，适合装各种种植介质，也适合配图，附盖设计，收纳也方便。'],
                [7, 161164, '来自英国的园艺工具，扎实耐用，不管是室内养植物还是户外花园，都能找到合适的工具。'],
                [7, 270144, '创立于1942年的丹麦陶盆世家，手工打造，天然透气，花盆界的颜值天花板。'],
            ],
        ];
        foreach ($config as $uid => $arr) {
            $activity = \Biz\service\activity\CreateWikiList::getInstance($uid);
            foreach ($arr as $v) {
                list($topic_id, $wiki_id, $msg) = $v;
                try {
                    $top = in_array($uid, $activity->hostUids) ? 1 : 2;
                    if ($wiki_id == 270243) $top = 0;
                    $activity->createGuidance($topic_id, $wiki_id, $msg, $top, true);
                } catch (Exception $e) {
                    echo "error:", implode("|", [$topic_id, $wiki_id, $msg, $e->getMessage()]), PHP_EOL;
                }
            }
        }
    }

    public function home(): array
    {
        $this->record('访问主页');
        $is_fav_map = mShopFavorite::is_favorited($this->uid, $this->awardWikiIds, mShopFavorite::TYPE_WIKI);
        $awards = [];
        foreach ($this->awardsConfig as $v) {
            list($id, $title, $cover_img, $logo) = $v;
            $is_fav = $is_fav_map[$id] ?? 0;
            $statSign = Basic::genStatSign(AutoPlatformModule::MODULE_INTEREST_APARTMENT_HOME_WIKI_CARD, [
                Basic::EXTEND_KEY_OBJ_ID => $id,
            ]);
            $virtual = !is_numeric($id);
            $awards[] = compact('id', 'title', 'cover_img', 'logo', 'is_fav', 'statSign', 'virtual');
        }
        shuffle($awards);
        //取清单热门列表，前10的商品信息滚动展示 + 取该商品第一条推荐语
        $topic_list = [];
        //取排行榜所有的id
        $rank = CCreateWikiList::getAllRank([1, 2, 3, 4, 5, 6, 7], 9);
        $ids = [];
        foreach ($rank as $v) {
            if ($v) $ids = array_merge($ids, array_keys($v));
        }
        $rs = empty($ids) ? [] : MActivityGoodBuyWiki::select('*', ['id' => $ids, 'status' => 0, 'ORDER' => ['top' => 'DESC', 'num' => 'DESC', 'id' => 'DESC']]);
        $goodBuyWiki = [];
        foreach ($rs as $v) {
            $goodBuyWiki[$v['topic_id']][] = $v;
        }
        $uids = array_column($rs, 'uid');
        $uids = array_unique($uids);
        $wikiIds = array_column($rs, 'wiki_id');
        $wikiInfo = \Biz\module\Classes\wiki\Wiki::getWikiBaseInfos($wikiIds);
        $wikiInfo = array_column($wikiInfo, 'cover_img', 'id');
        $userInfo = \Doraemon\model\Member::getUserInfoByIds(array_values($uids));
        $nickMap = array_column($userInfo, 'nick', 'uid');
        $pv = $this->allPv();
        //7大主题卡片排序 前一天第一位的卡片，第二天沉到最后
        $ids = range(1, 7);
        $start = "20221104";
        $day = (strtotime($this->date) - strtotime($start))/86400;
        $day = $day % 7;
        $ids = array_merge(array_slice($ids, $day, 7 - $day), array_slice($ids, 0, $day));
        foreach ($ids as $i) {
            $v = $this->topicConfig[$i];
            list($id, $title, $title_img, $cover_img, $detail_img, $link, $obj_ids, $linkId) = $v;
            $comment_list = [];
            $temp = $goodBuyWiki[$id] ?? [];
            foreach ($temp as $vv) {
                $comment_list[] = [
                    'comment_id' => $vv['id'],
                    'nick' => $nickMap[$vv['uid']] ?? '',
                    'comment' => $vv['recommend'],
                    'wiki_img' => $wikiInfo[$vv['wiki_id']] ?? current($wikiInfo),
                ];
            }
            $user = [
                'total' => (int)($pv[$id] ?? 0),
                'avatars' => self::rankCoverImg(3)
            ];
            shuffle($obj_ids);
            $obj_ids = array_slice($obj_ids, 0, 9);
            $note = \Doraemon\service\Format\Note\HandleNote::handleNote($obj_ids, \Doraemon\pockets\constInterface\FormatScene::BASE_INFO, 0);
            $relate_list = [];
            foreach ($note as $rid => $item) {
                $relate_list[] = [
                    'rid' => $rid,
                    'title' => $item['photo']['photo_info']['title'] ?: $item['photo']['photo_info']['remark'],
                    'cover_img' => $item['photo']['photo_info']['image_list'][0]['thumb_pic_url'] ?: $item['photo']['photo_info']['video_info']['thumb_pic_url'],
                    'user_info' => [
                        'nick' => $item['photo']['user_info']['nick'] ?? '',
                        'avatar' => $item['photo']['user_info']['small_avatar'] ?? '',
                    ],
                    'statSign' => Basic::genStatSign(AutoPlatformModule::MODULE_INTEREST_APARTMENT_HOME_NOTE, [
                        Basic::EXTEND_KEY_OBJ_ID => $rid,
                    ], ['information' => $title]),
                ];
            }
            $linkSign = strpos($link, 'topic') === false ? AutoPlatformModule::MODULE_INTEREST_APARTMENT_HOME_CIRCLE : AutoPlatformModule::MODULE_INTEREST_APARTMENT_HOME_TOPIC_CARD;
            $statSign = Basic::genStatSign(AutoPlatformModule::MODULE_INTEREST_APARTMENT_HOME_BANNER, [], ['information' => $title]);
            $linkStatSign = Basic::genStatSign($linkSign, [Basic::EXTEND_KEY_OBJ_ID => $linkId], ['information' => $title]);
            $topic_list[] = compact('id', 'title', 'title_img', 'cover_img', 'comment_list', 'user', 'link', 'relate_list', 'statSign', 'linkStatSign');
        }

        return [
            'award_list' => $awards,
            'lottery_times' => $this->getLotteryTimes(),
            'topic_list' => $topic_list
        ];
    }

    /**
     * 主题详情
     * share_info? + 封面图 + 文案 + share_task + create_task
     * 列表 page + sort_type + page_size
     *  list
     *      wiki_info (id title cover_img 价格)
     *      推荐语列表 (uid 用户头像 推荐语 楼主标识)
     *  count
     *  is_over
     *
     * @throws Exception
     */
    public function detail($topic_id, $sort_type = 1, $page = 1, $size = 20): array
    {
        $this->record('主题详情页访问,参数' . json_encode(compact('topic_id', 'sort_type', 'page', 'size'), JSON_UNESCAPED_UNICODE));
        //清单封面图
        //清单文案
        $detail = $this->topicConfig[$topic_id] ?? [];
        if (empty($detail)) throw new \Exception('未知主题，id：'. $topic_id);
        list($id, $title, $title_img, $cover_img, $detail_img, $link, $obj_ids, $linkId) = $detail;
        if (!in_array($sort_type, [1, 2])) $sort_type = 1; //1 最热 2 最新
        $sort = $sort_type == 1 ? ['top' => 'DESC', 'num' => 'DESC', 'updated_at' => 'DESC'] : ['updated_at' => 'DESC'];
        $offset = ($page - 1) * $size;
        $condition = ['topic_id' => $topic_id, 'status' => 0];
        $total = MActivityGoodBuyWiki::count($condition);

        $totalPage = ceil($total / $size);
        $rs = MActivityGoodBuyWiki::select('*', $condition + ['LIMIT' => [$offset, $size], 'ORDER' => $sort]);
        $wikiIds = array_column($rs, 'wiki_id');
        $recommendCondition = $condition + ['wiki_id' => $wikiIds, 'ORDER' => ['id' => 'DESC']];
        $rs = MActivityGoodBuyWikiRecommend::select('*', $recommendCondition);
        $uids = array_column($rs, 'uid');
        $uids = array_unique($uids);
        $member = \Doraemon\model\Member::getUserInfoByIds(array_values($uids));
        foreach ($member as $v) {
            list($avatar,) = \Doraemon\service\User::getUserAvatarPicUrl($v['uid'], $v['avatar_version']);
            $avatarMap[$v['uid']] = $avatar;
        }

        $wikiInfo = \Biz\module\Classes\wiki\Wiki::getWikiBaseInfos($wikiIds);
        $msg_list = [];
        foreach ($rs as $v) {
            $msg_list[$v['wiki_id']][] = [
                'id' => $v['id'],
                'uid' => $v['uid'],
                'avatar' => $avatarMap[$v['uid']] ?? '',
                'msg' => $v['recommend'],
                'host' => in_array($v['uid'], $this->hostUids) ? 1 : 0
            ];
        }
        $map = [];
        foreach ($wikiInfo as $v) {
            $temp = $msg_list[$v['id']] ?? [];
            $top = array_pop($temp);
            array_unshift($temp, $top);
            $map[$v['id']] = [
                'wiki_info' => [
                    'id' => $v['id'],
                    'title' => $v['simple_title'] ?: $v['title'],
                    'cover_img' => $v['cover_img'],
                    'min_price' => $v['min_price'],
                    'max_price' => $v['max_price'],
                    'price' => $v['min_price'],
                ],
                'statSign' => Basic::genStatSign(AutoPlatformModule::MODULE_INTEREST_APARTMENT_DETAILS_WIKI_CARD, [
                    Basic::EXTEND_KEY_OBJ_ID => $v['id'],
                ], ['tab' => $sort_type == 1 ? 'hot' : 'new', 'information' => $title]),
                'msg_list' => array_slice($temp, 0, 20)
            ];
        }
        $list = [];
        foreach ($wikiIds as $wikiId) {
            if (isset($map[$wikiId])) $list[] = $map[$wikiId];
        }
        $this->pv($topic_id);
        $this->record("主题[$topic_id]详情页 pv +1");

        $share_task = $this->getShareTaskMaxTimes() - $this->getFinishShareTask();
        $create_task = $this->getCreateTaskMaxTimes() - $this->getFinishCreateTask();
        return [
            'list' => $list,
            'title' => $title,
            'cover_img' => $detail_img,
            'user' => [
                'total' => (int)$this->getPv($topic_id),
                'avatars' => self::rankCoverImg(3)
            ],
            'count' => (int)$total,
            'is_over' => $page < $totalPage ? 0 : 1,
            'share_task' => $share_task > 0 ? $share_task : 0,
            'create_task' => $create_task > 0 ? $create_task : 0,
        ];

    }

    public function incrLotteryCounter($action = 'incr')
    {
        return $action == 'incr' ? CCreateWikiList::incrTaskCounter($this->lotteryTask, $this->uid) : CCreateWikiList::decrTaskCounter($this->lotteryTask, $this->uid);
    }

    public function getWinnerTask(): array
    {
        return CCreateWikiList::getAllTask($this->winnerTask);
    }

    public function setWinnerTask($id, $value)
    {
        return CCreateWikiList::setTaskCounter($this->winnerTask, $id, $value);
    }

    public function getFinishCreateTask()
    {
        return CCreateWikiList::getTaskCounter($this->createTask, $this->uid);
    }

    public function getFinishShareTask()
    {
        return CCreateWikiList::getTaskCounter($this->shareTask, $this->uid);
    }

    public function getLotteryTimes(): int
    {
        return (int)CCreateWikiList::getTaskCounter($this->lotteryTask, $this->uid);
    }

    public function finishShareTask()
    {
        $this->record('分享任务调用');

        if (empty($this->uid)) return;
        if (!$this->activityLiving()) return;

        //完成任务
        $finish = CCreateWikiList::incrTaskCounter($this->shareTask, $this->uid);

        if ($finish > $this->getShareTaskMaxTimes()) {
            return false;
        }
        //增加抽奖次数
        $this->incrLotteryCounter();
        $this->record('分享任务获取抽奖次数 +1');
    }

    public function userCache(): array
    {
        return [
            'create' => CCreateWikiList::getTaskCounter($this->createTask, $this->uid),
            'share' => CCreateWikiList::getTaskCounter($this->shareTask, $this->uid),
            'lottery' => CCreateWikiList::getTaskCounter($this->lotteryTask, $this->uid),
        ];
    }

    public function finishCreateTask()
    {
        if (!$this->activityLiving()) return;
        //完成任务
        $finish = CCreateWikiList::incrTaskCounter($this->createTask, $this->uid);

        if ($finish > $this->getCreateTaskMaxTimes()) {
            return false;
        }
        //增加抽奖次数
        $this->incrLotteryCounter();
    }
    

    public function lottery()
    {
        $award_id = 0;
        $award = null;
        $this->record('执行抽奖');
        try {
            if (!$this->activityLiving()) throw new \Exception('活动已结束');
            if (empty($this->uid)) throw new \Exception('登录后操作');
            //扣减抽奖次数
            $times = $this->getLotteryTimes();
            if ($times > 0) {
                $this->incrLotteryCounter('decr');
            } else {
                throw new \Exception('抽奖次数已用完');
            }

            //规则校验
            $rule = \Biz\service\activity\lottery\LotteryActivityRules::getInstance($this->uid, $this->did, -1);
            if (!$rule->exec()) {
                throw new \Exception(current($rule->error()));
            }

            //注册时间在2022年1月1日之前的用户才有可能中奖
            $userInfo = \Doraemon\model\Member::getUserInfoByIds([$this->uid]);
            $addtimeMap = array_column($userInfo, 'addtime', 'uid');
            if (($addtimeMap[$this->uid] ?? time()) > strtotime("2022-01-01")) throw new \Exception('注册时间在2022年1月1日之前的用户才有可能中奖');
            if (CCreateWikiList::hasWinner($this->uid)) throw new \Exception('每个用户活动期间内最多中奖一次');
            if (rand(1, 100) != 1) throw new \Exception('每个用户每次抽奖的中奖概率均为5%');

            //加锁执行
            if (empty($this->gap_lock = CCreateWikiList::lock()))  throw new Exception('奖品发放间隔控制');

            //追加商品
            $this->appendGift();
            //选择商品库
            $gift = CCreateWikiList::popGiftPool();

            $awardConfig = $this->awardsConfig[$gift] ?? [];
            if (empty($awardConfig)) throw new Exception('奖品库为空');
            list($id, $title, $cover_img, $logo) = $awardConfig;

            //中奖记录id = 中奖名单长度 + 1
            $award_id = CCreateWikiList::countWinner() + 1;
            //用户标记
            CCreateWikiList::addWinner($this->uid);
            //用户中奖信息
            $this->setWinnerTask($award_id, json_encode(compact('gift', 'award_id', 'title')));

            $award = [
                'name' => $title,
                'cover_img' => $cover_img,
            ];

            //中奖后触发行为
            $this->winningMsg($award_id);

            $userInfo = \Doraemon\model\Member::getUserInfoByIds([$this->uid]);
            $nickMap = array_column($userInfo, 'nick', 'uid');
            $product = "wiki_id:$gift($title)";
            \Biz\model\activity\ActivityAward::addData(0, $this->activity_id, $this->uid, $this->now(), $nickMap[$this->uid] ?? '', $product);
            $this->record('中奖');
        } catch (\Exception $e) {
            $this->record('未中奖原因,' . $e->getMessage());
        }

        //奖品信息
        return [
            'award_id' => $award_id,
            'award' => $award,
            'lottery_times' => $this->getLotteryTimes(),
        ];
    }

    /**
     * @throws Exception
     */
    public function receiveRecordCreate($award = '', $name = '', $encrypt_phone_id = '', $delivery_address = '')
    {
        try {
            if (empty($this->uid)) throw new \Exception('登录后操作');
            $this->record('填写收货地址,参数' . json_encode(compact('award', 'name', 'encrypt_phone_id', 'delivery_address'), JSON_UNESCAPED_UNICODE));
            //检查中奖信息是否匹配
            $awards = $this->getWinnerTask();
            if (empty($awards[$award])) throw new \Exception('没有中奖信息');
            if (ActivityAwardDelivery::hasData($this->activity_id, $this->uid, $award)) throw new \Exception('你已提交过地址啦～如需要修改地址请私信联系@好好住福利官');
            ActivityAwardDelivery::addData(0, $this->activity_id, $this->uid, $award, $name, $encrypt_phone_id, $delivery_address);
        } catch (\Exception $e) {
            $this->record('填写收货地址错误原因,' . $e->getMessage());
            throw $e;
        }
    }

    public function clearAllCache()
    {
        echo "删除日志:", $this->cache_handler::clearLog(), PHP_EOL;
        echo "删除主题信息:", CCreateWikiList::clearRank([1,2,3,4,5,6,7]), PHP_EOL;
        echo "删除奖池信息:", CCreateWikiList::clearGiftPool(), PHP_EOL;
        $winner = CCreateWikiList::allWinner();
        foreach ($winner as $uid) {
            echo "删除用户[$uid]中奖信息信息:", CCreateWikiList::clearAllTask($this->winnerKey($uid)), PHP_EOL;
        }
        echo "删除中奖用户:", CCreateWikiList::clearWinner(), PHP_EOL;
        echo "删除pv:", CCreateWikiList::clearAllTask($this->pvTask), PHP_EOL;
        $start = '20221026';
        $lotteryKeys = [];
        $shareKeys = [];
        $createKeys = [];
        foreach (range(0, 17) as $i) {
            $date = date("Ymd", strtotime($start) + $i * 86400);
            $lotteryKeys[] = $this->lotteryKey($date);
            $shareKeys[] = $this->shareKey($date);
            $createKeys[] = $this->createKey($date);
        }
        echo "删除[$start~$date]抽奖纪录:", CCreateWikiList::clearAllTask($lotteryKeys), PHP_EOL;
        echo "删除[$start~$date]分享纪录:", CCreateWikiList::clearAllTask($shareKeys), PHP_EOL;
        echo "删除[$start~$date]创建纪录:", CCreateWikiList::clearAllTask($createKeys), PHP_EOL;

    }

    public function reset()
    {
        //清空表
        MActivityGoodBuyWiki::query("TRUNCATE TABLE " . MActivityGoodBuyWiki::_TABLE_NAME);
        MActivityGoodBuyWikiRecommend::query("TRUNCATE TABLE " . MActivityGoodBuyWikiRecommend::_TABLE_NAME);
        //清空缓存
        $this->clearAllCache();
        //初始化pv
        foreach (range(1, 7) as $topic_id) {
            $this->pv($topic_id);
        }
        //初始化奖池
        $this->initGiftPool();
        //初始化静态资源
        self::prepareGuidance();
    }

    public function monitoring()
    {
        while (true) {
            try {
                list(, $msg) = $this->cache_handler::popLog();
                $msg = explode("|", $msg);
                foreach ($msg as $v) {
                    echo $v, PHP_EOL;
                }
                echo "-------------------", PHP_EOL;
            } catch (\Exception $e) {
                echo "error:", $e->getMessage(), PHP_EOL;
            }
        }
    }

    public function winningMsg($award_id)
    {
        $link = Hhzurl::getDomain() . "/activity/address?award_id=$award_id";
        $nlink = Common::formatLinkNormalLink($link);
        $title = '恭喜你在双十一活动中奖啦！';
        $desc = '请即刻填写收货信息；7日内有效，逾期即视为自动放弃奖品！';
        $cover_img = 'https://img.haohaozhu.cn/Op-imageShow/8a36d308c08c07z00rkeqmv?iv=1';
        LotteryActivityMsg::imSend($this->uid, $title, $desc, $cover_img, $nlink);
    }

    /**
     * @throws Exception
     */
    public function wordTrial($msg)
    {
        $remarkForbidden = new ForbiddenSceneWord(ForbiddenSceneWordModel::CONTENT, $msg);
        if ($remarkForbidden->getHit() && !$remarkForbidden->getPublish()) throw new Exception("内容中包含禁用词");
    }

    protected function now()
    {
        return date("Y-m-d H:i:s");
    }

    protected function winnerKey($uid): string
    {
        return 'winner:' . $uid;
    }

    protected function shareKey($date): string
    {
        return $date . 'share';
    }
    protected function createKey($date): string
    {
        return $date . 'create';
    }
    protected function lotteryKey($date): string
    {
        return $date . 'lottery';
    }
}